package com.yupi.yupao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.constant.UserConstant;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.mapper.UserMapper;
import com.yupi.yupao.utils.AlgorithmUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.yupi.yupao.constant.UserConstant.ADMIN_ROLE;
import static com.yupi.yupao.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author zy
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2024-07-19 19:29:41
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT="yupi";

    /**
     * 用户注册
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param checkPassword 校验密码
     * @param planetCode 星球编号
     * @return 新用户 id
     */
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword,checkPassword,planetCode)){
            //TODO  修改为自定义异常
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        if(userAccount.length()<4){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(userPassword.length()<8||checkPassword.length()<8){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(planetCode.length()>5){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 密码和校验密码相同
        if(!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 账户不能重复
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        long count=userMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 星球编号不能重复
        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("planetCode",planetCode);
        count=userMapper.selectCount(queryWrapper);
        if(count>0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 2. 加密
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());

        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if(!saveResult){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount   用户账户
     * @param userPassword  用户密码
     * @param request
     * @return 登录（脱敏）后的用户信息
     */
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if(StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if(userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(userPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 2. 加密
        String encryptPassword= DigestUtils.md5DigestAsHex((SALT+userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        queryWrapper.eq("userPassword",encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if(user==null){
            log.info("user login failed,userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }

        //3.用户脱敏
        User safetyUser=getSafetyUser(user);

        //4、记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE,safetyUser);
        return safetyUser;
    }



    /**
     * 更新用户信息
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        log.info("更新用户信息新：{},旧:{}",user,loginUser);
        long userId = user.getId();
        if(userId<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如来是管理员。允许更新任意用户
        //如果不是管理员，只允许更新自己的信息
        if(!isAdmin(loginUser)&&userId!=loginUser.getId()){
            throw new BusinessException(ErrorCode.NO_AUIH);
        }
        User userOld=userMapper.selectById(userId);
//        User userOld=this.getById(user.getId());
        if(userOld==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
//        return this.baseMapper.updateById(user);
    }


    /**
     * 获取当前用户信息
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        if(request==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Object  userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        System.out.println(userObj);
        if(userObj==null){
            throw new BusinessException(ErrorCode.NO_AUIH);
        }
        return(User) userObj;
    }

    /**
     * 是否是管理员
     * @param request
     * @return
     */

    public boolean isAdmin(HttpServletRequest request) {
        Object userObj=request.getSession().getAttribute(USER_LOGIN_STATE);
        User user=(User) userObj;
        return user!=null &&user.getUserRole()==UserConstant.ADMIN_ROLE;
    }
    /**
     * 是否是管理员
     * @param loginUser
     * @return
     */
    public boolean isAdmin(User loginUser) {
        return loginUser!=null && loginUser.getUserRole()== UserConstant.ADMIN_ROLE;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public int userLogOut(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 用户脱敏
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser){
        if(originUser==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser=new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setTags(originUser.getTags());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setProfile(originUser.getProfile());
        safetyUser.setCreateTime(originUser.getCreateTime());

        return safetyUser;
    }


    /**
     * 根据标签搜索用户
     *
     * @param tagsNameList
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagsNameList){
        if(CollectionUtils.isEmpty(tagsNameList)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //sql查询
//        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
//        // like
//        for(String tagName:tagsNameList){
//            queryWrapper=queryWrapper.like("tags",tagName);
//        }
//        List<User> userList=userMapper.selectList(queryWrapper);
//        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());

        //内存查询
        //1.先查询所有用户
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        List<User> userList=userMapper.selectList(userQueryWrapper);

        Gson gson=new Gson();
        //2.在内存中判断包含的标签
        return userList.stream().filter(user -> {
            String tagsStr=user.getTags();
//            if(StringUtils.isBlank(tagsStr)){
//                return false;
//            }
            Set<String> tagNameSet=gson.fromJson(tagsStr,new TypeToken<Set<String>>(){}.getType());
            tagNameSet= Optional.ofNullable(tagNameSet).orElse(new HashSet<>());

            for(String tagName:tagsNameList){
                if(!tagNameSet.contains(tagName)){
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 匹配用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User>  matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","tags");
        queryWrapper.isNotNull("tags");
        List<User> userList=this.list(queryWrapper);
        String tags=loginUser.getTags();
        Gson gson=new Gson();
        List<String> tagList=gson.fromJson(tags,new TypeToken<List<String>>(){}.getType());
        // 用户列表的下标 => 相似度
        List<Pair<User,Long>> list=new ArrayList<>();
        // 依次计算所有用户和当前用户的相似度
        for(int i=0;i<userList.size();i++){
            User user=userList.get(i);
            String userTags=user.getTags();
            // 无标签或者为当前用户自己
            if(StringUtils.isBlank(userTags)|| user.getId().equals(loginUser.getId())){
                continue;
            }
            List<String> userTagList=gson.fromJson(userTags,new TypeToken<List<String>>(){}.getType());
            //计算分数
            long distance= AlgorithmUtils.minDistance(tagList,userTagList);
            list.add(new Pair<>(user,distance));
        }
        // 按编辑距离由小到大排序
        List<Pair<User,Long>> topUserPairList=list.stream()
                .sorted((a,b)->(int) (a.getValue()-b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        // 原本顺序的 userId 列表
        List<Long> userIdList=topUserPairList.stream()
                .map(pair ->pair.getKey().getId()).collect(Collectors.toList());
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.in("id",userIdList);
        // 1, 3, 2
        // User1、User2、User3
        // 1 => User1, 2 => User2, 3 => User3
        Map<Long,List<User>> userIdUserListMap=this.list(userQueryWrapper)
                .stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> finalUserList=new ArrayList<>();
        for (Long userId:userIdList){
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }

        return finalUserList;
    }
}




